import { ValidationPipe, UseInterceptors, UploadedFile, MaxFileSizeValidator, FileTypeValidator, HttpException, Controller, Get, Post, Body, Patch, Param, Delete, ParseIntPipe, ParseFilePipe, ParseUUIDPipe, Query, ParseArrayPipe, ParseEnumPipe, DefaultValuePipe, UsePipes } from '@nestjs/common';
import { PipeTestService } from './pipe-test.service';
import { CreatePipeTestDto } from './dto/create-pipe-test.dto';
import * as uuId from 'uuid';
import { FileInterceptor } from '@nestjs/platform-express';
import { ValidationPipeG } from '../common/pipe'

enum TestEnum {
  A = 'A',
  B = 'B',
}

/**
 * 管道测试
 */
@Controller('pipe-test')
export class PipeTestController {
  constructor(private readonly pipeTestService: PipeTestService) { }

  /**
   * get请求校验
   */
  @Get()
  getIndex() {
    console.log('uuid--', uuId.v4());
    return 'pipe-test'
  }

  @Get('/test')
  getTest(@Query('testId', new ValidationPipeG()) testId: string) {
    console.log('testId--', testId);
    return 'pipe-test'
  }

  @Get('/uuid')
  findAll(@Query('uuid', ParseUUIDPipe) uuid: string) {
    // 参数uuid校验通过会往下执行,2dc44875-d813-4b5e-9849-9760abf4cc18
    return this.pipeTestService.findAll();
  }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    console.log('id--', typeof id);
    return this.pipeTestService.findOne(+id);
  }

  @Get('/test2/:id')
  find(@Param('id', new ParseIntPipe({
    errorHttpStatusCode: 404, // 可以自定义错误码
    exceptionFactory: (errors) => {
      console.log(errors);
      return new HttpException('自定义错误信息', 400);
    }// 可以自定义错误信息
  })) id: number) {
    console.log('id--', typeof id);
    return this.pipeTestService.findOne(+id);
  }


  @Get('/test3/:id') // /test23/1,2,3 => 返回了0123，没有转类型
  find2(@Param('id', new ParseArrayPipe({})) arr: number[]) {
    return arr.reduce((pre, cur) => pre + cur, 0);
  }

  @Get('/test4/:id') // /test4/1,2,3 =>6 正常计算了
  find3(@Param('id', new ParseArrayPipe({
    items: Number, // 指定数组中的元素类型
    separator: ',' // 指定分隔符
  })) arr: number[]) {
    return arr.reduce((pre, cur) => pre + cur, 0);
  }


  @Get('/test5/:enum') // 枚举
  find5(@Param('enum', new ParseEnumPipe(TestEnum)) e: TestEnum) {
    return e
  }

  @Get('/test6')
  find6(@Query('v', new DefaultValuePipe('12')) v: string) {
    return v
  }

  /**
   post请求用dto校验
   dto设置类型，然后引入管道new ValidationPipe()
    */

  @Post('/save')
  // @UsePipes(new ValidationPipe())
  save(@Body(new ValidationPipe()) createPipeTestDto: CreatePipeTestDto) {
    return createPipeTestDto.name
  }

  @Post('file')
  @UseInterceptors(
    FileInterceptor('aaa', { // 读取字段
      dest: 'images', // 文件目录
    }),
  )
  // 限制文件大小类型
  uploadFile(@UploadedFile(new ParseFilePipe({
    validators: [
      new MaxFileSizeValidator({ maxSize: 1000000 }),
      new FileTypeValidator({ fileType: 'image/jpeg' }),
    ],
  })) file: Express.Multer.File, @Body() body) {
    console.log('body', body);
    console.log('file', file);
  }

}
